package com.scs.application.modules.sys.schedule;

import com.scs.application.modules.sys.entity.ScheduleJob;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 */
public class StaticMethodInvokeTask extends AbstractTask {

    private static Logger logger = LoggerFactory.getLogger(StaticMethodInvokeTask.class);

    private static final String PATTERN = "^(.*)\\.([\\w_]*?)\\((.*?)\\)$";

    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        JobDataMap mergedJobDataMap = context.getMergedJobDataMap();
        ScheduleJob job = (ScheduleJob) mergedJobDataMap.get(ScheduleJob.class.getName());
        String invokeTarget = job.getInvokeTarget();


        try {
            Pattern pattern = Pattern.compile(PATTERN);
            Matcher matcher = pattern.matcher(invokeTarget);
            matcher.find();

            resolveParameters(matcher.group(3));
            Object[] params = getParameters();
            Class[] paramClasses = getParametersType();


            Class<?> aClass = Thread.currentThread().getContextClassLoader().loadClass(matcher.group(1));
            Method method = aClass.getMethod(matcher.group(2), paramClasses);
            boolean isStatic = Modifier.isStatic(method.getModifiers());
            if (!isStatic) {

            }else{
                method.invoke(aClass, params);
            }
        } catch (Exception e) {
            throw new JobExecutionException(e);
        }
    }


    /**
     * 检查调用字符串是否是静态调用
     *
     * @param invokeTarget
     */
    public static boolean checkValidation(String invokeTarget) {
        Pattern pattern = Pattern.compile(PATTERN);
        Matcher matcher = pattern.matcher(invokeTarget);
        return matcher.matches();
    }

}
